package com.venusj.edu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/autodeliver")
public class AutodeliverController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/checkState/{userId}")
    public Integer findResumeOpenState(@PathVariable Long userId) {
        Integer forObject =
                restTemplate.getForObject("http://localhost:8080/resume/openstate/" + userId,
                        Integer.class);
        System.out.println("======>>>调⽤简历微服务，获取到⽤户" + userId + "的默认简历当前状态为： " + forObject);
        return forObject;
    }

    @GetMapping("/checkStateCloud/{userId}")
    public Integer findResumeOpenStateByCloud(@PathVariable Long userId) {
        // 1 选获取eureka中注册的resume-service实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("service-resume");

        // 2 获取实例（不进行负载均衡）
        ServiceInstance serviceInstance = instances.get(0);

        String host = serviceInstance.getHost();
        Integer port = serviceInstance.getPort();
        String url = "http://" + host + ":" + port + "/resume/openstate/" + userId;
        Integer forObject =
                restTemplate.getForObject(url,
                        Integer.class);
        System.out.println("======>>>调⽤简历微服务，获取到⽤户" + userId + "的默认简历当前状态为： " + forObject);
        return forObject;
    }

    @GetMapping("/getMetadata")
    public Integer getMetadata() {
        // 1 选获取eureka中注册的resume-service实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("service-resume");

        for(ServiceInstance serviceInstance : instances)
        {
            Map<String, String> metadata = serviceInstance.getMetadata();
            System.out.println("自定义元数据输出==》" + metadata.keySet());
        }
        return 0;
    }
}